package com.onlineshopping.interceptor;

import com.onlineshopping.entity.Result;
import com.onlineshopping.enums.ReturnCode;
import com.onlineshopping.exception.CustomerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;


@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 优先处理空指针异常
     * @param e 异常
     */
    @ExceptionHandler(value = {NullPointerException.class})
    @ResponseBody
    public Object nullPointerExceptionHandler(HttpServletRequest request, NullPointerException e){
        LOGGER.error("发生空指针异常，请求地址：{}, 错误信息：{}", request.getRequestURI(), e.getMessage());
        return Result.error(ReturnCode.RC500.getCode(), e.getMessage());
    }

    /**
     * 处理自定义的异常
     * @param e 异常
     */
    @ExceptionHandler(value = {CustomerException.class})
    @ResponseBody
    public Object customerExceptionHandler(HttpServletRequest request, CustomerException e){
        LOGGER.error("发生业务异常，请求地址：{}, 错误信息：{}", request.getRequestURI(), e.getMessage());
        return Result.error(ReturnCode.RC500.getCode(), e.getMessage());
    }

    /**
     * 兜底处理其它异常
     * @param e 异常
     */
    @ExceptionHandler(value = {Exception.class})
    @ResponseBody
    public Object exceptionHandler(HttpServletRequest request, Exception e){
        LOGGER.error("未知异常，请求地址：{}, 错误信息：{}", request.getRequestURI(), e.getMessage());
        return Result.error(ReturnCode.RC500.getCode(), e.getMessage());
    }

}




